<!--
  ~  Copyright (C) 2020 justlive1
  ~
  ~  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
  ~  in compliance with the License. You may obtain a copy of the License at
  ~
  ~  http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~  Unless required by applicable law or agreed to in writing, software distributed under the License
  ~  is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  ~  or implied. See the License for the specific language governing permissions and limitations under
  ~  the License.
  -->

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta content="IE=edge" http-equiv="X-UA-Compatible">
  <title>Easy Proxy</title>

  <link href="${ctx}/public/css/index.css" rel="stylesheet">
  <link href="${ctx}/public/layui/2.5.5/css/layui.css" rel="stylesheet">
</head>
<body>
<div class="layui-layout-body layui-layout-admin">
  <div class="layui-header header">
    <div class="layui-main">
      <div class="layui-form component"></div>
    </div>
  </div>

  <div class="layui-side layui-bg-black">
    <ul class="layui-nav layui-nav-tree" lay-filter="navs">
      <li class="layui-nav-item layui-nav-itemed layui-this"><a>客户端管理</a>
      </li>
      <li class="layui-nav-item"><a>数据统计</a></li>
    </ul>
  </div>
  <div class="layui-tab layui-body" lay-filter="tabs">
    <ul class="layui-tab-title layui-hide">
      <li class="layui-this" lay-id="客户端管理">客户端管理</li>
      <li lay-id="数据统计">数据统计</li>
    </ul>
    <div class="layui-tab-content">
      <div class="layui-tab-item layui-show">
        <table id="client_table" lay-filter="client_table"></table>
      </div>
      <div class="layui-tab-item">
        <table id="metrics_table" lay-filter="metrics_table"></table>
      </div>
    </div>
  </div>
</div>
<script src="${ctx}/public/layui/2.5.5/layui.js" type="text/javascript"></script>
<script type="text/html" id="toolbar_tpl">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
    <button class="layui-btn layui-btn-sm" lay-event="delBatch">删除</button>
  </div>
</script>
<script type="text/html" id="bar_tpl">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="proxy">代理</a>
</script>
<script type="text/html" id="client_status_tpl">
  {{# if (d.online) { }}
  <span class="layui-badge layui-bg-green">在线</span>
  {{# } else { }}
  <span class="layui-badge layui-bg-gray">离线</span>
  {{# } }}
</script>
<script type="text/html" id="bar_proxy_tpl">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="client_add_tpl">
  <form class="layui-form" style="margin-top:20px">
    <div class="layui-form-item">
      <label class="layui-form-label">客户端名称</label>
      <div class="layui-input-inline">
        <input type="text" name="name" lay-verify="required" placeholder="请输入" autocomplete="off"
               class="layui-input" value="{{d.name || ''}}">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">客户端秘钥</label>
      <div class="layui-input-inline">
        <input type="text" name="key" lay-verify="required" placeholder="请输入" autocomplete="off"
               class="layui-input" id="client_key_input" value="{{d.key || ''}}">
      </div>
      <a class="layui-form-mid layui-word-aux" onclick="randomId();"><i
          class="layui-icon">&#xe9aa;</i></a>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label"></label>
      <button class="layui-btn" lay-submit lay-filter="btn_client_add">确定</button>
      </button>
    </div>
  </form>
</script>
<script type="text/html" id="client_add_proxy_tpl">
  <form class="layui-form" id="client_add_proxy_form" style="margin-top:20px">
    <div class="layui-form-item">
      <label class="layui-form-label">代理名称</label>
      <div class="layui-input-inline">
        <input type="text" name="name" lay-verify="required" placeholder="请输入" autocomplete="off"
               class="layui-input" value="{{d.name || ''}}">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">映射地址</label>
      <div class="layui-input-inline">
        <input type="text" name="remote" lay-verify="required" placeholder="格式：127.0.0.1:80"
               autocomplete="off"
               class="layui-input" value="{{d.remote || ''}}">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">公网端口</label>
      <div class="layui-input-inline">
        <input type="text" name="port" lay-verify="required" placeholder="请输入" autocomplete="off"
               class="layui-input" value="{{d.port || ''}}">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label"></label>
      <input type="hidden" name="id" value="{{d.id || ''}}"/>
      <button class="layui-btn" lay-submit lay-filter="btn_client_proxy_add">确定</button>
      </button>
    </div>
  </form>
</script>
<script type="text/javascript">
  layui.use(['element', 'form', 'table', 'laytpl'], function () {

    layui.$.ajaxSetup({
      complete: function (resp) {
        if (resp.responseJSON && resp.responseJSON.code === '10000') {
          location.href = '${ctx}';
        }
      }
    });

    layui.element.on('nav(navs)', function (elem) {
      layui.element.tabChange('tabs', elem.text());
      layui.table.reload('client_table');
      layui.table.reload('metrics_table');
    });

    layui.table.render({
      id: 'client_table',
      elem: '#client_table',
      url: '${ctx}/client',
      skin: 'line',
      toolbar: '#toolbar_tpl',
      cols: [[{
        type: 'checkbox'
      }, {
        field: 'name',
        title: '客户端名称',
        width: 200
      }, {
        field: 'key',
        title: '客户端密钥'
      }, {
        field: 'online',
        title: '是否在线',
        width: 200,
        templet: "#client_status_tpl"
      }, {
        field: 'address',
        title: '客户端地址'
      }, {
        title: '操作',
        align: 'center',
        toolbar: '#bar_tpl'
      }]]
    });

    layui.table.on('toolbar(client_table)', function (obj) {
      if (obj.event === 'add') {
        layer.open({
          type: 1,
          area: ['350px', '230px'],
          content: layui.laytpl(layui.$('#client_add_tpl').html()).render({})
        });
      } else if (obj.event === 'delBatch') {
        var selects = layui.table.checkStatus('client_table').data.map(function (item) {
          return item.key;
        });
        if (selects.length === 0) {
          layer.alert('请选择要删除的客户端');
          return;
        }
        layer.confirm('确定要批量删除?', {icon: 3, title: '提示'}, function (index) {
          layui.$.ajax({
            url: '${ctx}/client',
            method: 'delete',
            data: {
              keys: selects.join()
            },
            success: function (resp) {
              if (resp.success) {
                layui.table.reload('client_table');
              } else {
                layer.alert(resp.message);
              }
            }
          });
          layer.close(index);
        })
      }
    });

    layui.table.on('tool(client_table)', function (obj) {
      if (obj.event === 'del') {
        layer.confirm('确定要删除[' + obj.data.name + ']?', {icon: 3, title: '提示'}, function (index) {
          layui.$.ajax({
            url: '${ctx}/client',
            method: 'delete',
            data: {
              keys: obj.data.key
            },
            success: function (resp) {
              if (resp.success) {
                layui.table.reload('client_table');
              } else {
                layer.alert(resp.message);
              }
            }
          });
          layer.close(index);
        });
      } else if (obj.event === 'edit') {
        layer.open({
          type: 1,
          title: '编辑',
          area: ['350px', '230px'],
          content: layui.laytpl(layui.$('#client_add_tpl').html()).render(obj.data)
        });
      } else if (obj.event === 'proxy') {
        layer.open({
          type: 1,
          title: '代理',
          area: ['800px', '400px'],
          content: '<div class="mg10"><table id="client_proxy_table" lay-filter="client_proxy_table"></table></div>',
          success: function () {
            layui.table.render({
              id: 'client_proxy_table',
              elem: '#client_proxy_table',
              url: '${ctx}/proxy/' + obj.data.key,
              skin: 'line',
              toolbar: '#toolbar_tpl',
              cols: [[{
                type: 'checkbox'
              }, {
                field: 'id',
                title: '编号',
                width: 100
              }, {
                field: 'name',
                title: '代理名称'
              }, {
                field: 'remote',
                title: '客户端映射地址',
                width: 200
              }, {
                field: 'port',
                title: '公网端口',
                width: 100
              }, {
                title: '操作',
                width: 150,
                align: 'center',
                toolbar: '#bar_proxy_tpl'
              }]]
            });

            layui.$("#client_proxy_table").data('key', obj.data.key);
          }
        });
      }
    });

    layui.form.on('submit(btn_client_add)', function (obj) {
      layui.$.post('${ctx}/client', obj.field, function (resp) {
        if (resp.success) {
          layer.closeAll();
          layui.table.reload('client_table');
        } else {
          layer.alert(resp.message);
        }
      });
      return false;
    });

    layui.table.on('toolbar(client_proxy_table)', function (obj) {
      if (obj.event === 'add') {
        layer.open({
          type: 1,
          area: ['350px', '280px'],
          content: layui.laytpl(layui.$('#client_add_proxy_tpl').html()).render({}),
          success: function (layero, index) {
            layui.$("#client_add_proxy_form").data("index", index);
          }
        });
      } else if (obj.event === 'delBatch') {
        var selects = layui.table.checkStatus('client_proxy_table').data.map(function (item) {
          return item.id;
        });
        if (selects.length === 0) {
          layer.alert('请选择要删除的代理');
          return;
        }
        layer.confirm('确定要批量删除?', {icon: 3, title: '提示'}, function (index) {
          layui.$.ajax({
            url: '${ctx}/proxy/' + layui.$("#client_proxy_table").data('key'),
            method: 'delete',
            data: {
              ids: selects.join()
            },
            success: function (resp) {
              if (resp.success) {
                layui.table.reload('client_proxy_table');
              } else {
                layer.alert(resp.message);
              }
            }
          });
          layer.close(index);
        })
      }
    });

    layui.form.on('submit(btn_client_proxy_add)', function (obj) {
      layui.$.post('${ctx}/proxy/' + layui.$("#client_proxy_table").data('key'), obj.field,
          function (resp) {
            if (resp.success) {
              layui.table.reload('client_proxy_table');
              layer.close(layui.$("#client_add_proxy_form").data("index"));
            } else {
              layer.alert(resp.message);
            }
          });
      return false;
    });

    layui.table.on('tool(client_proxy_table)', function (obj) {
      if (obj.event === 'del') {
        layer.confirm('确定要删除[' + obj.data.name + ']?', {
          icon: 3,
          title: '提示'
        }, function (index) {
          layui.$.ajax({
            url: '${ctx}/proxy/' + layui.$("#client_proxy_table").data('key'),
            method: 'delete',
            data: {
              ids: obj.data.id
            },
            success: function (resp) {
              if (resp.success) {
                layui.table.reload('client_proxy_table');
              } else {
                layer.alert(resp.message);
              }
            }
          });
          layer.close(index);
        });
      } else if (obj.event === 'edit') {
        layer.open({
          type: 1,
          title: '编辑',
          area: ['350px', '280px'],
          content: layui.laytpl(layui.$('#client_add_proxy_tpl').html()).render(obj.data),
          success: function (layero, index) {
            layui.$("#client_add_proxy_form").data("index", index);
          }
        });
      }
    });

    layui.table.render({
      id: 'metrics_table',
      elem: '#metrics_table',
      url: '${ctx}/metrics',
      skin: 'line',
      cols: [[{
        field: 'port',
        title: '端口'
      }, {
        field: 'createAt',
        title: '创建时间',
        templet: function (d) {
          return layui.util.timeAgo(d.createAt);
        }
      }, {
        field: 'readBytes',
        title: '流入流量',
        templet: function (d) {
          return bytesToSize(d.readBytes);
        }
      }, {
        field: 'writeBytes',
        title: '流出流量',
        templet: function (d) {
          return bytesToSize(d.writeBytes);
        }
      }, {
        field: 'channels',
        title: '连接数(服务端/客户端)',
        templet: function (d) {
          return d.serverChannels + "/" + (d.clientChannels > -1 ? d.clientChannels : '-');
        }
      }]]
    });

  });

  function randomId() {
    layui.$("#client_key_input").val('xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/[x]/g, function () {
      return (Math.random() * 16 | 0).toString(16);
    }));
  }

  function bytesToSize(bytes) {
    if (bytes === 0) {
      return '0 B';
    }
    var k = 1024, sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  }

</script>
</body>
</html>